package ecustom.common;

import weaver.general.GCONST;
import weaver.hrm.User;
import weaver.hrm.UserManager;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TestInitServet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void init(ServletConfig config) {
		if (GCONST.getServerName() == null || GCONST.getServerName().isEmpty()) {
			GCONST.setServerName("ecology");
		}
		if (GCONST.getRootPath() == null || GCONST.getRootPath().isEmpty()) {
			GCONST.setRootPath(config.getServletContext().getRealPath("/"));
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String method = request.getParameter("method");
		try {
			if ("changeLoginUser".equals(method)) changeLoginUser(request, response);
			else if ("getLoginUser".equals(method)) getLoginUser(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			response.getOutputStream().write(("Server error: " + e).getBytes());
		}
	}

	/** 修改登录用户 */
	private void changeLoginUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int userId = Integer.parseInt(request.getParameter("id"));
		User user = new UserManager().getUserByUserIdAndLoginType(userId, "1");
		request.getSession().setAttribute("weaver_user@bean", user);
		response.getOutputStream().write(("Current login user: " + user.getLoginid()).getBytes());
	}

	/** 获取登录用户 */
	private void getLoginUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		User user = (User)request.getSession().getAttribute("weaver_user@bean");
		if (user == null) {
			response.getOutputStream().write(("Session timeout, please login again.").getBytes());
			return ;
		}
		response.getOutputStream().write(("Login user: " + user.getLoginid()).getBytes());
	}
}